﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Linq;
using System.IO;
using System.Reflection;
using System.Diagnostics;
using IWshRuntimeLibrary;
namespace SetupHotel.DBCustomAction
{
    [RunInstaller(true)]
    public partial class DBCustomAction : Installer
    {
        public DBCustomAction()
        {
            InitializeComponent();
        }
        

        //执行sql 语句
        private void ExecuteSql(string conn, string DatabaseName, string Sql)
        {
            System.Data.SqlClient.SqlConnection mySqlConnection = new System.Data.SqlClient.SqlConnection(conn);
            System.Data.SqlClient.SqlCommand Command = new System.Data.SqlClient.SqlCommand(Sql, mySqlConnection);
            Command.Connection.Open();
            Command.Connection.ChangeDatabase(DatabaseName);
            try
            {
                Command.ExecuteNonQuery();
            }
            finally
            {
                //close Connection
                Command.Connection.Close();
            }
        }
        public override void Install(System.Collections.IDictionary stateSaver)
        {
            base.Install(stateSaver);
            // ------------------------建立数据库-------------------------------------------------
            if (this.Context.Parameters["setupdb"] == "1")
            {
                try
                {
                    string connStr = string.Format("data source={0};user id={1};password={2};persist security info=false;packet size=4096", this.Context.Parameters["server"], this.Context.Parameters["user"], this.Context.Parameters["pwd"]);
                    //根据输入的数据库名称建立数据库
                    ExecuteSql(connStr, "master", "create database   " + this.Context.Parameters["dbname"]);
                    //调用osql执行脚本
                    Process sqlProcess = new Process();
                    sqlProcess.StartInfo.FileName = "osql.exe";
                    sqlProcess.StartInfo.Arguments = String.Format(" -U {0} -P {1} -S {2} -d {4} -i {3}db.sql", this.Context.Parameters["user"], this.Context.Parameters["pwd"], this.Context.Parameters["server"], this.Context.Parameters["targetdir"], this.Context.Parameters["dbname"]);
                    sqlProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                    sqlProcess.Start();
                    sqlProcess.WaitForExit();  //等待执行
                    sqlProcess.Close();
                    //删除脚本文件
                    System.IO.FileInfo sqlFileInfo = new System.IO.FileInfo(string.Format("{0}\\DB.sql", this.Context.Parameters["targetdir"]));
                    if (sqlFileInfo.Exists)
                    {
                        {
                            sqlFileInfo.Delete();
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw (ex);
                }
            }
            // ---------------------将连接字符串写入Web.config-----------------------------------
            try
            {
                System.IO.FileInfo FileInfo = new System.IO.FileInfo(this.Context.Parameters["targetdir"] + "\\hotel.Win.exe.config");
                if (!FileInfo.Exists)
                {
                    throw (new InstallException("没有找到配置文件"));
                }
                //实例化xml文档
                System.Xml.XmlDocument XmlDocument = new System.Xml.XmlDocument();
                XmlDocument.Load(FileInfo.FullName);
                //查找到appsettings中的节点
                System.Xml.XmlNode Node;
                bool FoundIt = false;
                foreach (System.Xml.XmlNode tempLoopVar_Node in XmlDocument["configuration"]["connectionStrings"])
                {
                    Node = tempLoopVar_Node;
                    if (Node.Name == "add")
                    {
                        if (Node.Attributes.GetNamedItem("name").Value == "hotelEntities")
                        {
                            //写入连接字符串
                            Node.Attributes.GetNamedItem("connectionString").Value = string.Format("metadata=res://*/HotelModel.csdl|res://*/HotelModel.ssdl|res://*/HotelModel.msl;provider=System.Data.SqlClient;provider connection string='Persist Security Info=False;Data Source={0};Initial Catalog={1};User ID={2};Password={3};Packet Size=4096;Pooling=true;Max Pool Size=100;Min Pool Size=1';", this.Context.Parameters["server"], this.Context.Parameters["dbname"], this.Context.Parameters["user"], this.Context.Parameters["pwd"]);                           
                            FoundIt = true;
                        }
                        else if (Node.Attributes.GetNamedItem("name").Value == "hotelEntitiesThread")
                        {
                            //写入连接字符串
                            Node.Attributes.GetNamedItem("connectionString").Value = string.Format("metadata=res://*/HotelModel.csdl|res://*/HotelModel.ssdl|res://*/HotelModel.msl;provider=System.Data.SqlClient;provider connection string='Packet Size=4096;Persist Security Info=False;Data Source={0};Initial Catalog={1};User ID={2};Password={3};Pooling=true;Max Pool Size=50;Min Pool Size=1';", this.Context.Parameters["server"], this.Context.Parameters["dbname"], this.Context.Parameters["user"], this.Context.Parameters["pwd"]);
                            FoundIt = true;
                        }
                    }
                }
                foreach (System.Xml.XmlNode tempLoopVar_Node in XmlDocument["configuration"]["log4net"])
                {
                    Node = tempLoopVar_Node;
                    if (Node.Name == "add")
                    {
                        if (Node.Attributes.GetNamedItem("name").Value == "hotelEntities")
                        {
                            //写入连接字符串
                            Node.Attributes.GetNamedItem("connectionString").Value = string.Format("metadata=res://*/HotelModel.csdl|res://*/HotelModel.ssdl|res://*/HotelModel.msl;provider=System.Data.SqlClient;provider connection string='Persist Security Info=False;Data Source={0};Initial Catalog={1};User ID={2};Password={3};Packet Size=4096;Pooling=true;Max Pool Size=100;Min Pool Size=1';", this.Context.Parameters["server"], this.Context.Parameters["dbname"], this.Context.Parameters["user"], this.Context.Parameters["pwd"]);
                            FoundIt = true;
                        }
                        else if (Node.Attributes.GetNamedItem("name").Value == "hotelEntitiesThread")
                        {
                            //写入连接字符串
                            Node.Attributes.GetNamedItem("connectionString").Value = string.Format("metadata=res://*/HotelModel.csdl|res://*/HotelModel.ssdl|res://*/HotelModel.msl;provider=System.Data.SqlClient;provider connection string='Packet Size=4096;Persist Security Info=False;Data Source={0};Initial Catalog={1};User ID={2};Password={3};Pooling=true;Max Pool Size=50;Min Pool Size=1';", this.Context.Parameters["server"], this.Context.Parameters["dbname"], this.Context.Parameters["user"], this.Context.Parameters["pwd"]);
                            FoundIt = true;
                        }
                    }
                }
                //log4net的数据库配置
                foreach (System.Xml.XmlNode tempLoopVar_Node in XmlDocument["configuration"]["log4net"]["appender"])
                {

                    Node = tempLoopVar_Node;

                    if (Node.Name == "connectionString")
                    {
                        Node.Attributes.GetNamedItem("value").Value = string.Format("server={0};Initial Catalog={1};User ID={2};Password={3};Pooling=true;Max Pool Size=50;Min Pool Size=1;", this.Context.Parameters["server"], this.Context.Parameters["dbname"], this.Context.Parameters["user"], this.Context.Parameters["pwd"]); ;
                        FoundIt = true;
                    }
                }
                if (!FoundIt)
                {
                    throw (new InstallException("hotel.Win.exe.config文件没有包含connString连接字符串设置"));
                }
                XmlDocument.Save(FileInfo.FullName);

                System.Reflection.Assembly Asm = System.Reflection.Assembly.LoadFrom(this.Context.Parameters["targetdir"] + "\\hotel.Win.exe");//获取当前程序集信息
                System.IO.FileInfo fileinfo = new System.IO.FileInfo(Asm.Location);//获取当前程序集位置
                string dbpath = fileinfo.DirectoryName;//获取文件夹名称                
                //在桌面创建快捷方式
                WshShell shell = new WshShell();
                IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(
                    Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "\\人和酒店系统.lnk"
                    );

                shortcut.TargetPath = Asm.Location;//目标
                shortcut.WorkingDirectory = dbpath;//工作文件夹
                shortcut.WindowStyle = 1;//窗体的样式：１为默认，２为最大化，３为最小化
                shortcut.Description = "";//快捷方式的描述
                shortcut.IconLocation = Asm.Location;//图标
                shortcut.Save();


            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }
    }
}
